package web023.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import web023.model.User;
import web023.service.HelloService;

import javax.validation.Valid;
import java.util.List;


@Controller
@RequestMapping(value = {"/web", "/mvc"})
public class HelloController {


    @Autowired
    private HelloService helloService;

    @RequestMapping(value = "/hi", method = RequestMethod.GET)
    @ResponseBody
    public String hi() {
        int num=1/0;
        return "hi web";
    }

    @RequestMapping(value = "/hello/{name}", method = RequestMethod.GET)
    public String hello(@PathVariable("name") String name, Model model) {
        List<User> users = helloService.changeName(name);
        model.addAttribute("users", users);
        return "hello";
    }


    @RequestMapping(value = "/to/add", method = RequestMethod.GET)
    public String toAdd() {
        return "add";
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String saveUpdate(@Valid User user, Errors errors) {
        if (errors.hasErrors()) {
            List<ObjectError> allErrors = errors.getAllErrors();
            for (ObjectError error : allErrors) {
                //输出文字提示（正式使用可以直接返回到页面中）
                System.out.println(error.getDefaultMessage());
            }
            return "add";
        }
        System.out.println(user.getId());
        System.out.println(user.getName());
        return "redirect:/web/to/add";
    }


    @RequestMapping(value = "/to/update", method = RequestMethod.GET)
    public String toUpdate(Model model) {
        model.addAttribute("user", new User(123, "Jack"));
        return "add";
    }


}


